import { useIntersectionObserver } from '@vueuse/core'
import { onBeforeMount, onBeforeUnmount, onMounted, onUnmounted, ref } from 'vue';
import { useIntervalFn } from '@vueuse/core'
export function uselazyLoadData(fun: () => void) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
    // console.log(isIntersecting);
    if (isIntersecting) {
      fun()
      stop()
    }
  }, {
    threshold: 0
  })
  return target
}

//吸顶效果
export function useScroll() {
  //滚动距离大于78显示 小于78隐藏
  onMounted(() => {
    window.addEventListener('scroll', onscroll)
  })
  const y = ref(0)
  const onscroll = () => {
    // console.log('滚动');
    const top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    // console.log(top);
    y.value = top
  }
  //组件销毁前 解绑对于的组件的事件
  onBeforeUnmount(() => {
    window.removeEventListener('scroll', onscroll)
  })
  return y
}

//倒计时hook
export function useCountDown(startnum: number = 5) {
  const count = ref(0)
  //利用vueuse里的useIntervalFn来处理定时器功能
  const { pause, resume } = useIntervalFn(() => {
    count.value--
    // console.log(123);
    if (count.value <= 0) pause()
  }, 1000, { immediate: false })
  const start = () => {
    count.value = startnum
    resume()
  }
  // useIntervalFn 内部已经做了组件销毁 停止定时器这个操作了
  // onUnmounted(()=>{pause})
  return {
    resume,
    count,
    start
  }
}